<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <title>购物车</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f9f9f9;
        }
        .cart-container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h2 {
            color: #4CAF50;
            margin-bottom: 20px;
            text-align: center;
        }
        /* 表格样式 */
        .cart-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .cart-table th, .cart-table td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: center;
        }
        .cart-table th {
            background-color: #4CAF50;
            color: white;
        }
        .cart-table tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        /* 操作按钮样式 */
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        .btn {
            padding: 6px 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
        }
        .btn:hover {
            background-color: #45a049;
        }
        .btn.delete {
            background-color: #e74c3c;
        }
        .btn.delete:hover {
            background-color: #c0392b;
        }
        /* 数量控制 */
        .quantity-control {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .quantity-btn {
            width: 25px;
            height: 25px;
            background: #f5f5f5;
            border: 1px solid #ddd;
            cursor: pointer;
        }
        .quantity-btn:hover {
            background-color: #e6e6e6;
        }
        .quantity-input {
            width: 40px;
            height: 25px;
            text-align: center;
            margin: 0 5px;
            border: 1px solid #ddd;
        }
        /* 底部结算区域 */
        .cart-footer {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
            padding: 15px;
            background-color: #f5f5f5;
        }
        .total-price {
            font-size: 18px;
            font-weight: bold;
            color: #e4393c;
        }
        .checkout-btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 30px;
            cursor: pointer;
            font-size: 16px;
            border-radius: 4px;
        }
        .checkout-btn:hover {
            background-color: #45a049;
        }
        /* 响应式设计 */
        @media (max-width: 768px) {
            .cart-table {
                display: block;
                overflow-x: auto;
            }
            .cart-footer {
                flex-direction: column;
                gap: 15px;
            }
        }
        /* 复选框样式 */
        .select-all {
            margin-right: 15px;
        }
    </style>
</head>
<body>
<div class="cart-container">
    <h2>我的购物车</h2>

    <!-- 购物车表格 -->
    <table class="cart-table">
        <thead>
        <tr>
            <th><input type="checkbox" id="select-all" class="select-all"></th>
            <th>购物车ID</th>
            <th>订单ID</th>
            <th>用户ID</th>
            <th>食物ID</th>
            <th>单价</th>
            <th>数量</th>
            <th>加入时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach items="${shopcartList}" var="cart">
            <tr data-id="${cart.shopcartid}">
                <td><input type="checkbox" class="item-select" checked></td>
                <td>${cart.shopcartid}</td>
                <td>${cart.orderid}</td>
                <td>${cart.userid}</td>
                <td>${cart.recipeid}</td>
                <td>¥${cart.price}</td>
                <td>
                    <div class="quantity-control">
                        <button class="quantity-btn minus">-</button>
                        <input type="text" class="quantity-input" value="${cart.num}">
                        <button class="quantity-btn plus">+</button>
                    </div>
                </td>
                <td>${cart.createtime}</td>
                <td class="action-buttons">
                    <button class="btn delete delete-btn">删除</button>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>

    <!-- 底部结算区域 -->
    <div class="cart-footer">
        <div>
            <button class="btn" id="delete-selected">删除选中</button>
            <a href="${pageContext.request.contextPath}/foods/list" class="btn">继续购物</a>
        </div>
        <div style="display: flex; align-items: center; gap: 20px;">
            <div>已选 <span id="selected-count">${fn:length(shopcartList)}</span> 件</div>
            <div>总计: <span class="total-price" id="total-price">¥<fmt:formatNumber value="${totalPrice}" pattern="#.##"/></span></div>
            <button class="checkout-btn" id="checkout-btn">去结算</button>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        // 计算单个商品总价
        function calculateItemTotal(item) {
            const price = parseFloat(item.find('td:nth-child(6)').text().substring(1)); // 第6列是单价
            const quantity = parseInt(item.find('.quantity-input').val());
            return price * quantity;
        }

        // 更新总计
        function updateTotalPrice() {
            let total = 0;
            let selectedCount = 0;

            $('tbody tr').each(function() {
                if ($(this).find('.item-select').is(':checked')) {
                    total += calculateItemTotal($(this));
                    selectedCount++;
                }
            });

            $('#total-price').text('¥' + total.toFixed(2));
            $('#selected-count').text(selectedCount);
        }

        // 数量增减
        $('.quantity-btn').click(function() {
            const input = $(this).siblings('.quantity-input');
            let quantity = parseInt(input.val());

            if ($(this).hasClass('minus') && quantity > 1) {
                quantity--;
            } else if ($(this).hasClass('plus')) {
                quantity++;
            }

            input.val(quantity);
            updateTotalPrice();
            updateCartItem($(this).closest('tr'));
        });

        // 数量输入框变化
        $('.quantity-input').change(function() {
            if (isNaN(this.value) || this.value < 1) {
                this.value = 1;
            }
            updateTotalPrice();
            updateCartItem($(this).closest('tr'));
        });

        // 更新购物车商品
        function updateCartItem(item) {
            const shopcartid = item.data('id');
            const num = item.find('.quantity-input').val();

            $.ajax({
                url: '${pageContext.request.contextPath}/shopcart/update',
                type: 'POST',
                data: {
                    shopcartid: shopcartid,
                    num: num
                },
                success: function(response) {
                    console.log('更新成功:', response);
                },
                error: function(xhr) {
                    console.error('更新失败:', xhr.responseText);
                }
            });
        }

        // 单个商品删除
        $('.delete-btn').click(function() {
            const item = $(this).closest('tr');
            const shopcartid = item.data('id');

            if (confirm('确定要删除此商品吗？')) {
                $.ajax({
                    url: '${pageContext.request.contextPath}/shopcart/delete/' + shopcartid,
                    type: 'POST',
                    success: function(response) {
                        item.remove();
                        updateTotalPrice();
                        alert('删除成功');
                    },
                    error: function(xhr) {
                        alert('删除失败: ' + xhr.responseText);
                    }
                });
            }
        });

        // 全选/取消全选
        $('#select-all').change(function() {
            $('.item-select').prop('checked', this.checked);
            updateTotalPrice();
        });

        // 单个选择框变化
        $('.item-select').change(function() {
            updateTotalPrice();
            // 检查是否全部选中
            const allChecked = $('.item-select').length === $('.item-select:checked').length;
            $('#select-all').prop('checked', allChecked);
        });

        // 删除选中商品
        $('#delete-selected').click(function() {
            const selectedItems = [];
            $('.item-select:checked').each(function() {
                selectedItems.push($(this).closest('tr').data('id'));
            });

            if (selectedItems.length === 0) {
                alert('请至少选择一件商品');
                return;
            }

            if (confirm('确定要删除选中的' + selectedItems.length + '件商品吗？')) {
                $.ajax({
                    url: '${pageContext.request.contextPath}/shopcart/deleteBatch',
                    type: 'POST',
                    data: {
                        ids: selectedItems.join(',')
                    },
                    success: function(response) {
                        $('.item-select:checked').each(function() {
                            $(this).closest('tr').remove();
                        });
                        updateTotalPrice();
                        alert('删除成功');
                    },
                    error: function(xhr) {
                        alert('删除失败: ' + xhr.responseText);
                    }
                });
            }
        });

        // 结算按钮点击事件
        $('#checkout-btn').click(function() {
            const $btn = $(this);
            const selectedItems = [];

            $('.item-select:checked').each(function() {
                selectedItems.push($(this).closest('tr').data('id'));
            });

            if (selectedItems.length === 0) {
                alert('请至少选择一件商品');
                return;
            }

            // 禁用按钮防止重复提交
            $btn.prop('disabled', true).text('处理中...');

            $.ajax({
                url: '${pageContext.request.contextPath}/order/create',
                type: 'POST',
                data: {
                    shopcartIds: selectedItems.join(',')
                },
                success: function(response) {
                    console.log('完整响应:', response);

                    if (response && response.status === "success" && response.orderid) {
                        alert('订单创建成功!');
                        const orderId = encodeURIComponent(response.orderid);
                        window.location.href = '${pageContext.request.contextPath}/order/detail/' + orderId;
                    } else {
                        alert('订单创建失败: ' + (response.message || '服务器未返回订单ID'));
                        $btn.prop('disabled', false).text('去结算');
                    }
                },
                error: function(xhr) {
                    console.error('错误详情:', xhr);
                    let errorMsg = '请求失败: ';

                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        errorMsg += errorResponse.message || xhr.statusText;
                    } catch (e) {
                        errorMsg += xhr.status + ' ' + xhr.statusText;
                    }

                    alert(errorMsg);
                    $btn.prop('disabled', false).text('去结算');
                }
            });
        });

        // 初始化计算总价
        updateTotalPrice();
    });
</script>
</body>
</html>